package com.client.common.interceptor;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSON;
import com.client.common.util.AuthContextUtil;
import com.client.model.pojo.user.ArUser;
import com.client.model.vo.common.Result;
import com.client.model.vo.common.ResultCodeEnum;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.concurrent.TimeUnit;

/**
 * 后端拦截器
 *
 * @Author：rulerwood
 * @DateTime： 2024/3/27 14:50
 * @PackageName: com.zt.manager.interceptor
 * @ClassName: LoginAuthInterceptor
 */
@Slf4j
@Component
public class LoginAuthInterceptor implements HandlerInterceptor {


    @Resource
    private RedisTemplate<String, String> redisTemplate;

    @Override
    //目标方法进行之前进行 前置通知
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //OPTIONS请求遇见不做拦截
        if ("OPTIONS".equals(request.getMethod())) {
            return true;
        }
        //获取请求头中的token
        String token = request.getHeader("token");
        if (StrUtil.isBlank(token)) {
            resoponseInfo(response);
            return false;
        }
        //通过前端的
        String s = redisTemplate.opsForValue().get("user:login:" + token);
        if (StrUtil.isBlank(s)) {
            resoponseInfo(response);
            return false;
        }

        //进行线程绑定
        ArUser arUser = JSON.parseObject(s, ArUser.class);
        AuthContextUtil.setUser(arUser);
        log.info("用户信息-------------------->{}", arUser);
        //延长登录时间
        redisTemplate.expire("user:login:" + token, 30, TimeUnit.MINUTES);
        return true;

    }

    @Override
    //目标方法执行之后进行 后置通知
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    //视图渲染之后进行 最终通知
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //清除用户
        AuthContextUtil.clear();
    }

    private void resoponseInfo(HttpServletResponse response) {
        Result result = Result.build(null, ResultCodeEnum.LOGIN_AUTH);
        response.setStatus(401);
        response.setContentType("application/json;charset=utf-8");
        response.setCharacterEncoding("utf-8");
        try {
            PrintWriter writer = response.getWriter();
            writer.println(JSON.toJSONString(result));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


}
